/**
 * @created by kongqf on 2019-12-5 09:36:02
 * @updated by
 * @description jobFlowGraph
 */
// 注意js引用顺序
define([
  './custom/widgets/js/yufpSelectParam.js',
  './pages/use/apps/jobManager/jobFlowGraph/jobFlowGraph.css',
  './libs/mxgraph/libs/init.js',
  './libs/mxgraph/libs/sanitizer.min.js',
  './libs/mxgraph/libs/editorUi.js',
  './libs/mxgraph/libs/editor.js',
  './libs/mxgraph/libs/sidebar.js',
  './libs/mxgraph/libs/graph.js',
  './libs/mxgraph/libs/format.js',
  './libs/mxgraph/libs/shapes.js',
  './libs/mxgraph/libs/actions.js',
  './libs/mxgraph/libs/menus.js',
  './libs/mxgraph/libs/toolbar.js',
  './libs/mxgraph/libs/dialogs.js',
  './custom/widgets/js/YuWorkflow.js'
], function (require, exports) {
  /**
   * 页面加载完成时触发
   * @param hashCode 路由ID
   * @param data 传递数据对象
   * @param cite 页面站点信息
   */
  exports.ready = function (hashCode, data, cite) {
    yufp.lookup.reg('USE_TASK_JOB_TYPE,USE_EVT_REL_TYPE,USE_FIXED_TIME_RANGE,USE_FIXED_TIME_F,USE_EVENT_TYPE');
    var size = yufp.frame.size();
    yufp.custom.vue({
      el: cite.el,
      data: function () {
        var _this = this;
        var check = function (rule, value, callback) {
          if (value === null || value === undefined || value === '') {
            callback(new Error('字段不能为空'));
          } else {
            callback();
          }
        };
        var limit = function (rule, value, callback) {
          if (value === null || value === undefined || value === '') {
            callback();
          } else {
            if (value.length !== 6 || !/^[0-9]+$/.test(value)) {
              callback(new Error('请输入六位时间格式'));
            } else {
              if (value.slice(0, 1) != 0 ? value.slice(0, 2) > 24 : false) {
                callback(new Error('小时数必须小于或等于24'));
              } else if (value.slice(2, 3) != 0 ? value.slice(2, 4) >= 60 : false) {
                callback(new Error('分钟数必须小于60'));
              } else if (value.slice(4, 5) != 0 ? value.slice(4) >= 60 : false) {
                callback(new Error('秒数必须小于60'));
              } else {
                callback();
              }
            }
          }
        };
        /*定义校验规则，只能填字母数字 下划线*/
        var valiCodes = function (rule, value, callback) {
          var reg = /^[0-9a-zA-Z_]{2,}$/;
          if (value && reg.test(value)) {
            if (value.length > 64) {
              callback(new Error('长度不能大于64位'));
            } else {
              callback();
            }
          } else if (value && !reg.test(value)) {
            callback(new Error('能填字母、数字和下划线(长度不得小于两位)'));
          } else {
            callback();
          }
        };
        /**检验数字为0-255*/
        var numMax = function (rule, value, callback) {
          if (value) {
            if (Number(value) >= 0 && Number(value) <= 255) {
              callback();
            } else {
              callback(new Error('必须为0-255之间'));
            }
          } else {
            callback();
          }
        };

        return {
          editDowIndex: 0,//默认选择编辑第一行参数内容
          ruleslist: {
            actionCode: [
              { validator: valiCodes, trigger: 'blur' }
            ]
          },
		  nodeExec:'required',
          cell: {},
          template: [],
          templateOptions: [],
          modelForm: {},
          disabledOpr: false,
          agentIds: [],
          isModify: true,
		  actionLoc2Rule:[{required: true,message: '必填项'}],
          limit: { validator: limit, trigger: 'blur' },
          rule: [{ required: true, validator: check, trigger: 'blur' },
          { validator: numMax, trigger: 'blur' }
          ],
          //校验天规则
          dayRules: [
            { validator: this.numCheck, trigger: 'blur' }
          ],
          height: size.height - 40,
          width: size.width,
          dialogVisible: false,
          dialogTitle: '',
          // disabledname:true,//不让修改作业代码
          formDisabled: false,
          showSidebar: false,
          circulationFormData: { minRet: 0, maxRet: 0, remark: '' },
          workBaseFormData: {},
          workExecFormData: { actionLoc: '' },
          workAdditionalFormData: { radio1: '1', radio2: '', radio3: '' },
          workData: {},
          filterText: '',
          options: [{
            key: 'Y',
            value: '是'
          }, {
            key: 'N',
            value: '否'
          }],
          nodetype: '',
          tableData1: [],
          radio1: true,
          radio2: true,
          radio3: true,
          timeList: [],
          dayList: [],
          selectTime: {},
          dateTypeOptions: [],
          treeData: [],
          visible: false,
          workTreeData: [],
          getData: { wftParList: [], useEventCrossList: [], autoUseEventCrossList: [] },
          getSlectId: [],
          treeTempData: [],
          isHiddenAction: false,
          isHiddenActionSelect: false,
          actionLocOptions: [],
          paramObj: {
            appCode: data.appCode
          },
          isExce: false,
          isProcess: false,
          isPasted: false, // 是否是复制粘贴出来的节点
          tabsValue: 'baseMsg',
          row: [],
          appCode: data.appCode,
          actionTips: {
            '+': '用户定义的作业流',
            '-': '空作业',
            'C': '操作系统命令或可执行程序和脚本',
            'D': 'IBM DataStage Job',
            'F': '动态连接库中的函数，至多含有16个仅字符串类型的固定个数的参数',
            'H': 'Restful服务',
            'I': 'Informatica PowerCenter Session',
            'J': 'Java类中的静态方法',
            'M': '没有输出参数的数据库存储过程',
            'Q': 'SQL语句',
            'R': '具有整数型唯一输出参数的数据库存储过程',
            'S': '具有整数型返回值的数据库存储过程',
            'T': 'Oracle Tuxedo Servic',
            'V': '动态连接库中的函数，含有仅字符串类型的可变个数的参数',
            'W': 'Webservice',
          },
          actionLogTips: {
            '+': '请选择应用系统',
            '-': '无需填写',
            'C': '请填写执行用户，不填则使用默认用户',
            'D': '请填写驱动位置',
            'F': '无需填写',
            'H': '无需填写',
            'I': '无需填写',
            'J': '请填写驱动位置',
            'M': '请填写数据源',
            'Q': '请填写数据源',
            'R': '请填写数据源',
            'S': '请填写数据源',
            'T': '无需填写',
            'V': '无需填写',
            'W': '无需填写',
          },
          weekMap: {
            '0': '日',
            '1': '一',
            '2': '二',
            '3': '三',
            '4': '四',
            '5': '五',
            '6': '六'
          },
          currentTips: '',
          tip4ActionLoc: '',
          rules: { paramName: [{ required: true, message: '请输入参数名称', trigger: 'blur' }], paramValue: [{ required: true, message: '请输入参数值', trigger: 'blur' }] },
          newFlag: '1',
          scale: 6,
          selectCellDialogTitle: '',
          showSelectCellDialog: false,
          isSelectNextCell: false,
          selectionCell: {},
          tableCells: [],
          multipleSelection: [],
          // 依赖作业查询
          jobFieldDatas: [{
            placeholder: '作业名称',
            field: 'actionName',
            type: 'input'
          }],
          // 依赖作业查询按钮
          jobButtons: [{
            label: '搜索',
            op: 'submit',
            type: 'primary',
            click: function (model, valid) {
              model.appCode = _this.workBaseFormData.appCode;
              model.groupCode = data.groupCode;
              // model.actionCode = _this.workBaseFormData.actionCode;
              var param = { condition: JSON.stringify(model) };
              _this.$refs.jobTableRef.remoteData(param);
            }
          }, {
            label: '确定', op: 'submit', type: 'primary',
            click: function (model, valid) {
              var selectArr = _this.$refs.jobTableRef.selections;
              var relJob = "";
              var exitArr = [];
              if (!_this.getData.autoUseEventCrossList) {
                _this.getData.autoUseEventCrossList = [];
              }
              yufp.clone(_this.getData.autoUseEventCrossList, exitArr);
              if (selectArr.length > 0) {
                for (var i = 0; i < selectArr.length; i++) {
                  var flag = true;
                  for (var j = 0; j < exitArr.length; j++) {
                    if (selectArr[i].actionCode == exitArr[j].actionCode
                      && selectArr[i].groupCode == exitArr[j].groupCode
                      && selectArr[i].appCode == exitArr[j].appCode) {
                      flag = false;
                    }
                  }
                  if (flag) {
                    relJob += selectArr[i].actionCode + ";";
                    _this.getData.autoUseEventCrossList.push(selectArr[i]);
                  }
                }
                relJob = relJob.substring(0, relJob.length - 1);
              }
              if (_this.workBaseFormData.relJobs) {
                if (relJob != '') {
                  _this.workBaseFormData.relJobs += ";" + relJob;
                }
              } else {
                _this.workBaseFormData.relJobs = relJob;
              }
              _this.visible = false;
            }
          }, {
            label: '清除', op: 'submit', type: 'primary',
            click: function (model, valid) {
              _this.workBaseFormData.relJobs = '';
              _this.getData.autoUseEventCrossList.splice(0);
              _this.visible = false;
            }
          }],
          // 依赖作业查询url
          jobDataUrl: "api/use/plats/workflow/queryFlowNodeListByPage",
          jobFieldColumns: [
            { label: '应用系统', prop: 'appCode' },
            { label: '应用系统名称', prop: 'appName' },
            { label: '作业流代码', prop: 'groupCode' },
            { label: '作业编号', prop: 'actionCode' },
            { label: '作业名称', prop: 'actionName' }
          ],
          // 事件窗口
          eventVisible: false,
          // 事件查询
          eventFieldDatas: [{
            placeholder: '应用系统',
            field: 'appCode',
            type: 'select',
			options:[{'key':'','value':'全部'}]
          },{
            placeholder: '事件名称',
            field: 'eventName',
            type: 'input'
          },{
            placeholder: '事件代码',
            field: 'eventCode',
            type: 'input'
          }],
          // 事件查询按钮
          eventButtons: [{
            label: '搜索',
            op: 'submit',
            type: 'primary',
            click: function (model, valid) {
              var param = { condition: JSON.stringify(model) };
              _this.$refs.eventTableRef.remoteData(param);
            }
          }, {
            label: '确定', op: 'submit', type: 'primary',
            click: function (model, valid) {
              var selectArr = _this.$refs.eventTableRef.selections;
              if (selectArr.length < 1) {
                _this.$message('请先选择数据');
                return;
              }
              var selCHeck = [];
              if (!_this.getData.useEventCrossList) {
                _this.getData.useEventCrossList = [];
              }
              yufp.clone(_this.getData.useEventCrossList, selCHeck);
              for (var i = 0; i < selectArr.length; i++) {
                var flag = true;
                for (var j = 0; j < selCHeck.length; j++) {
                  if (selCHeck[j].eventCode == selectArr[i].eventCode) {
                    flag = false;
                  }
                }
                if (flag) {
                  selectArr[i].eventApp = selectArr[i].appCode;
                  selectArr[i].relation = 'D';//默认选则依赖
                  _this.getData.useEventCrossList.push(selectArr[i]);
                }
              }
              _this.eventVisible = false;
            }
          }],
          // 依赖作业查询url
          eventDataUrl: "api/use/plats/event/queryList",
          eventFieldColumns: [
            { label: '应用系统', prop: 'appCode' },
            { label: '应用系统名称', prop: 'appName' },
            { label: '事件代码', prop: 'eventCode' },
            { label: '事件名称', prop: 'eventName' },
            { label: '事件路径', prop: 'folderPath' },
            { label: '事件类型', prop: 'eventType', dataCode: "USE_EVENT_TYPE" }
          ],
          // 时间选择器值
          timepicker: "",
          timepickerList: [],
          execPanedisable: false
        };
      },
      watch: {
        timeList: function (val) {
          var _this = this;
          _this.workAdditionalFormData.timeList = val;
        },
        'workAdditionalFormData.radio1': function (val, o) {
          if (val) {
            this.workAdditionalFormData.radio2 = '';
            this.workAdditionalFormData.radio3 = '';
            this.radio1 = false;
            this.radio2 = true;
            this.radio3 = true;
          }
          if (this.workAdditionalFormData.radio2 == '' && this.workAdditionalFormData.radio3 == '') {
            this.workAdditionalFormData.radio1 = '1';
          }
        },
        'workAdditionalFormData.radio2': function (val) {
          if (val) {
            this.workAdditionalFormData.radio1 = '';
            this.workAdditionalFormData.radio3 = '';
            this.radio1 = true;
            this.radio2 = false;
            this.radio3 = true;
          }
        },
        'workAdditionalFormData.radio3': function (val) {
          if (val) {
            var _this = this;
            _this.workAdditionalFormData.radio1 = '';
            _this.workAdditionalFormData.radio2 = '';
            _this.radio1 = true;
            _this.radio2 = true;
            _this.radio3 = false;
          }
        }
      },
      created: function () {
        var _this = this;
        _this.queryWftAgtList();
        yufp.service.request({
          url: backend.useService + '/plats/calendar/queryUseCalendarTypeList',
          method: 'get',
          data: {
            appCode: data.appCode
          },
          callback: function (code, message, response) {
            if (response && response.data) {
              for (var i = 0; i < response.data.length; i++) {
                _this.dateTypeOptions.push({ key: response.data[i].typeCode, value: response.data[i].typeName });
              }
            }
          }
        });
        /* yufp.service.request({
          url: backend.useService + '/plats/event/queryTreeForForFlowchart',
          method: 'get',
          data: {
            appCode: data.appCode,
            groupCode: data.groupCode
          },
          callback: function (code, message, response) {
            if (response && response.data) {
              _this.treeData = yufp.clone(response.data, []);
              _this.treeTempData = yufp.clone(response.data, []);
            }
          }
        }); */
      },
      mounted: function () {
		  var _this = this;
        _this.$nextTick(function () {
          _this.workAdditionalFormData.radio1 = '1';
        })

		_this.getappList();

      },
      destroyed: function () {
        this.cell = null;
        this.template = null;
        this.modelForm = null;
        this.agentIds = null;
        this.limit = null;
        this.rule = null;
        this.circulationFormData = null;
        this.workBaseFormData = null;
        this.workAdditionalFormData = null;
        this.workData = null;
        this.tableData1 = null;
        this.timeList = null;
        this.dayList = null;
        this.selectTime = null;
        this.dateTypeOptions = null;
        this.treeData = null;
        this.workTreeData = null;
        this.getData = null;
        this.getSelectedData = null;
        this.treeTempData = null;
        this.actionLocOptions = null;
        this.row = null;
        this.rules = null;
        this.ruleslist = null;
        this.selectionCell = null;
        this.tableCells = null;
        this.multipleSelection = null;
        this.$off();
      },
      methods: {
		  getappList:function(){ //获取
				var _this = this;
				yufp.service.request({
					url:'api/use/plats/event/queryTreeList',
					method: 'get',
					data: {
					},
					callback: function(code, message, response) {
						if(response && response.data && response.data.length  > 0){
							var sl = [{'key':'','value':'全部'}];
							for(var it in response.data){
								var key = response.data[it].appCode;
								var value = response.data[it].appName;
								sl.push({'key':key,'value':value});
							}
							_this.eventFieldDatas[0].options = sl ;
						}
					},
				});
		  },
        /*对相对日期的天数增加校验    年，半年0-99； 季：0-90；旬 ，0-9；周0-6   */
        numCheck: function (rule, value, callback) {
          var _this = this;
          if (value) {
            if (isNaN(value) || Math.round(value) != value) { //为数字且为整数
              callback(new Error('只能为整数数字'));
            } else {
              var dateone = _this.workAdditionalFormData.date1;
              if (dateone) {
                if ('Y' == dateone || 'H' == dateone) { //年,半年
                  if (Number(value) >= 0 && Number(value) <= 99) {
                    callback();
                  } else {
                    callback(new Error('年须为1-99之间'));
                  }
                } else if ('Q' == dateone) { //季
                  if (Number(value) >= 0 && Number(value) <= 90) {
                    callback();
                  } else {
                    callback(new Error('季须为1-90之间'));
                  }
                } else if ('T' == dateone) { //旬
                  if (Number(value) >= 0 && Number(value) <= 9) {
                    callback();
                  } else {
                    callback(new Error('旬须为1-9之间'));
                  }
                } else if ('W' == dateone) { //周
                  if (Number(value) >= 0 && Number(value) <= 6) {
                    callback();
                  } else {
                    callback(new Error('周须为1-6之间'));
                  }
                } else if ('M' == dateone) { //月  未知
                  if (Number(value) >= 0 && Number(value) <= 30) {
                    callback();
                  } else {
                    callback(new Error('月须为1-30之间'));
                  }
                } else {
                  callback();
                }
              }

            }
            /* 		  		if(Number(value) >= 0 && Number(value) <=255 ){
                        callback();
                      }else{
                        callback(new Error('必须为0-255之间'));
                      } */
          } else {
            callback();
          }
        },
        getSelectedData: function (data) {
          var _this = this;
          //这里需要找到第几个在修改
          let clickIdex = _this.editDowIndex || 0;
          _this.$refs.refTableExec.data[clickIdex].paramName = data[0].paramName;
        },
        rowClickFn: function (row) {
          this.row = yufp.clone(row, {});
        },
        tableRowClassName({ row, rowIndex }) {
          //吧每一行的索引放入row
          row.index = rowIndex;
        },
        rowClickFnOne: function (row, column, cell, event) {
          this.editDowIndex = row.index;

        },
        relationChangeFn: function (val) {
          var _this = this;
          if (val === 'T' && _this.row.eventType === 'F') {
            for (var i = 0; i < _this.getData.useEventCrossList.length; i++) {
              if (_this.row.eventName === _this.getData.useEventCrossList[i].eventName) {
                this.getData.useEventCrossList[i].relation = 'D';
                //_this.$set(_this.getData.useEventCrossList[i],'relation','D')
                _this.$set(_this.getData.useEventCrossList, i, _this.getData.useEventCrossList[i]) //使vue识别该数组变化
                _this.$message({ message: '文件事件类型不能触发！', type: 'warning' });

                return;
              }
            }
          }
        },
        remoteData: function () { },
        /**
         * 初始化工作流
         */
        initGraph: function () {
          var _this = this;
          _this.createSidebar();
          yufp.service.request({
            url: backend.useService + '/plats/workflow/queryflowChart',
            method: 'get',
            data: {
              appCode: data.appCode,
              groupCode: data.groupCode
            },
            callback: function (code, message, response) {
              if (response && response.data) {
                _this.workData = response.data;
                _this.newFlag = response.data.newFlag;
                var notSetEdgeAnchorPoint = _this.newFlag == '1';
                var edgeData = _this.data2EdgeData(response.data.wftCndList);
                var cellData = _this.data2CellData(response.data.wftLstList);
                var vertexList = _this.$refs.refWorkflow.addVertexList(null, cellData);
                _this.$refs.refWorkflow.addEdgeList(null, edgeData, notSetEdgeAnchorPoint, vertexList);
                // 加载数据完成后结束提示并修改界面样式
                _this.$refs.refWorkflow.graphComplete();
              }
            }
          });
        },
        checkIncludes: function (arr, str) {
          for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === str) {
              return true;
            }
          }
          return false
        },
        /**
         * 切换执行位置修饰
         */
        selectTypeCodeFn: function (val, Obj) {
          var _this = this;
          this.execPanedisable = false;
          this.currentTips = this.actionTips[val] || '';
          this.tip4ActionLoc = this.actionLogTips[val] || '';

          this.workExecFormData.actionLoc = '';
          if (val === '+') {
            _this.isProcess = true;
          } else {
            _this.isProcess = false;
          }
          if (val === '-' || val === '+') {
           // this.workBaseFormData.agentCode = ' ';
            this.workBaseFormData.multiFlag = 'N';
            this.workBaseFormData.intrFlag = 'Y';
            this.disabledOpr = true;
          } else {
            this.disabledOpr = false;
          }
          if (val === '-') {
			  //为路由，不用写执行内容
			 this.nodeExec = '';
            this.isHiddenAction = true;
            this.isHiddenActionSelect = true;
            this.isExce = true;
            this.execPanedisable = true;
          } else if (val === '+' || val === 'D' || val === 'I' || val === 'J' || val === 'M' || val === 'R' || val === 'S' || val === 'T' || val === 'Q' || val === 'W') {
            this.nodeExec = 'required';
			this.isExce = false;
            this.isHiddenAction = true;
            this.isHiddenActionSelect = false;
            var urlObj = {
              '+': '/plats/apps/getTreeWftList',
              'D': '/plats/dscfg/queryList',
              'I': '/plats/pccfg/queryList',
              'J': '/plats/jccfg/queryList',
              'M': '/plats/rdbcfg/queryList',
              'R': '/plats/rdbcfg/queryList',
              'S': '/plats/rdbcfg/queryList',
              'Q': '/plats/rdbcfg/queryList',
              'T': '/plats/txdcfg/queryList',
              'W': '/plats/wscfg/queryList',
            }
            yufp.service.request({
              method: 'GET',
              url: backend.useService + urlObj[val],
              data: { appCode: data.appCode },
              async: false,
              callback: function (code, message, response) {
                if (response.code != 0) {
                  _this.$message(response.message);
                } else {
                  _this.actionLocOptions.splice(0);
                  var flag = false;
                  for (var i = 0; i < response.data.length; i++) {
                    if (response.data[i].classCode == _this.workExecFormData.actionLoc2) {
                      flag = true;
                    }
                    if (val === '+') {
                      if (response.data[i].appCode != '0000') {
                        _this.actionLocOptions.push({ key: response.data[i].appCode, value: response.data[i].appName });
                      }
                    } else {
                      _this.actionLocOptions.push({ key: response.data[i].classCode, value: response.data[i].className });
                    }
                  }
                  if (!flag) {
                    _this.workExecFormData.actionLoc2 = '';
                    _this.workExecFormData.actionLoc1 = ' ';
                  }
                  if (_this.actionLocOptions.length === 0) {
                    _this.isHiddenAction = false;
                    _this.isHiddenActionSelect = true;
                  }
                }
              }
            });
          } else {
            this.isExce = false;
            this.isHiddenAction = false;
            this.isHiddenActionSelect = true;
          }
        },
        /**
         * 加载集群代理名称
         */
        queryWftAgtList: function () {
          var _this = this;
          var paramObj = {};
          paramObj.appCode = data.appCode;
          yufp.service.request({
            method: 'GET',
            url: backend.useService + "/plats/apps/queryWftAgtList",
            data: paramObj,
            async: false,
            callback: function (code, message, response) {
              if (response.code != 0) {
                isOk = false;
                _this.$message(response.message);
              } else {
                _this.agentIds.splice(0);
                _this.agentIds.push({ key: " ", value: "虚拟代理" });
                for (let i = 0; i < response.data.length; i++) {
                  _this.agentIds.push({ key: response.data[i].agentCode, value: response.data[i].agentName+"("+response.data[i].agentCode+")" });
                }
              }
            }
          });
        },
        /**
         * 添加事件
         */
        addEventFn: function () {
          var _this = this;
          var selections = _this.$refs.msgTree.getCheckedNodes(true);
          if (selections.length === 0) {
            _this.$message({ message: '请选择事件!', type: 'warning' });
            return;
          }
          var selCHeck = _this.getData.useEventCrossList || [];
          //_this.getData.useEventCrossList = _this.getData.useEventCrossList || [];
          for (var j = 0; j < selections.length; j++) {
            for (var i = 0; i < selCHeck.length; i++) {
              if (selCHeck[i].eventCode == selections[j].id) {
                _this.$message({ message: '包含已添加事件!', type: 'warning' });
                return;
              }
            }
          }
          for (var i = 0; i < selections.length; i++) {
            selCHeck.push({ eventType: selections[i].busiType, eventApp: selections[i].appCode, eventName: selections[i].label, eventCode: selections[i].id, relation: 'D', reamrk: ' ' });
          }
          _this.$set(_this.getData, 'useEventCrossList', selCHeck); //给对象的数组添加属性，必须用set,不然vue.js无法监控数据变化
          _this.$nextTick(function () {
            _this.$refs.msgTree.setCheckedNodes([]);
          });
        },
        /**
         * 过滤树节点
         */
        getTree: function (treeData) {
          var arr = [];
          for (var i = 0; i < treeData.children.length; i++) {
            if (treeData.children[i].children && treeData.children[i].children.length > 0) {
              arr = arr.concat(this.getTree(treeData.children[i]));
            } else {
              arr.push(treeData.children[i]);
            }
          }
          return arr;
        },
        /**
         * 加载节点数据
         */
        getData2Form: function (data) {
          yufp.clone(data, this.workBaseFormData);
          // data.limitInfo = '1112@DT1M-01';
          var i = 0;
          var _this = this;
          this.timeList.splice(0);
          if (data.autoUseEventCrossList) {
            data.autoUseEventCrossList.forEach(function (list) {
              _this.getSlectId.push(list.treeId);
            });
          }
          while (data.limitInfo && i < data.limitInfo.trim().length) {

            if ((data.limitInfo.slice(i, i + 4)).indexOf('@DT') > -1) {
              var value = '';
              for (var j in this.dateTypeOptions) {
                if (this.dateTypeOptions[j].key == (data.limitInfo.slice(i, i + 4)).split('@DT')[1]) {
                  value = this.dateTypeOptions[j].value;
                  break;
                }
              }
              this.timeList.push({ key: data.limitInfo.slice(i, i + 4), value: value });
            } else if ((/^[0-9]+$/.test(data.limitInfo.slice(i, i + 4)))) {
              this.timeList.push({ key: data.limitInfo.slice(i, i + 4), value: data.limitInfo.slice(i, i + 4).slice(0, 2) + '月' + data.limitInfo.slice(i, i + 4).slice(2, 4) + '日' });
            } else {
              this.timeList.push({ key: data.limitInfo.slice(i, i + 4), value: yufp.lookup.convertKey('USE_FIXED_TIME_RANGE', data.limitInfo.slice(i, i + 4).slice(0, 1)) + yufp.lookup.convertKey('USE_FIXED_TIME_F', data.limitInfo.slice(i, i + 4).slice(1, 2)) + data.limitInfo.slice(i, i + 4).slice(2, 4) + '天' });
            }
            i = i + 4;
          }
        },
        /**
         * 将接口数据转换成graph节点数据
         */
        data2CellData: function (data) {
          var _this = this;
          var cells = [];
          var baseY = 160;
          var size = 50;
          var maxY = this.getCellsMaxY();
          if (data && data.length > 0) {
            baseY = data[0].positionY
          }
          // 添加开始结束节点
          cells.push({
            id: '.<@START@>.',
            nodetype: '.<@START@>.',
            value: '',
            x: data.length > 0 ? _this.workData.posBeginX * _this.scale : -100,
            y: _this.newFlag == '1' ? -(_this.workData.posBeginY - maxY) * _this.scale : data.length > 0 ? -_this.workData.posBeginY * _this.scale : baseY,
            width: size,
            height: size,
            style: 'image;image=libs/mxgraph/images/workflow/wstart.png;',
            relative: false,
            data: {
              positionX: _this.workData.posBeginX,
              positionY: _this.workData.posBeginY
            }
          });
          data.forEach(function (item, index) {
            cells.push({
              id: item.actionCode,
              nodetype: item.typeCode,
              value: item.actionName,
              x: item.positionX * _this.scale,
              y: _this.newFlag == '1' ? -(item.positionY - maxY) * _this.scale : -item.positionY * _this.scale,
              width: size,
              height: size,
              style: 'image;image=libs/mxgraph/images/workflow/' + item.typeCode + '.png;',
              relative: false,
              data: item
            })
          })
          cells.push({
            id: '.<@END@>.',
            nodetype: '.<@END@>.',
            value: '',
            x: data.length > 0 ? _this.workData.posEndX * _this.scale : 400,
            y: _this.newFlag == '1' ? -(_this.workData.posEndY - maxY) * _this.scale : data.length > 0 ? -_this.workData.posEndY * _this.scale : baseY,
            width: size,
            height: size,
            style: 'image;image=libs/mxgraph/images/workflow/wend.png;',
            relative: false,
            data: {
              positionX: _this.workData.posEndX,
              positionY: _this.workData.posEndY
            }
          });
          return cells;
        },
        getCellsMaxY: function () {
          var yArr = [this.workData.posBeginY, this.workData.posEndY];
          this.workData.wftLstList.forEach(function (item) {
            yArr.push(item.positionY);
          });
          return Math.max.apply(Math, yArr);
        },
        /**
         * 将接口数据转换成graph连线数据
         */
        data2EdgeData: function (data) {
          var cells = [];
          data.forEach(function (item) {
            cells.push({
              nodetype: 'EDGE',
              id: (item.condAction.trim() || '.<@START@>.') + '-' + (item.actionCode.trim() || '.<@END@>.'),
              value: '',
              path: item.flowPath,
              remark: item.remark || '',
              style: item.drawInfo || '',
              data: item,
              source: item.condAction.trim() || '.<@START@>.',
              target: item.actionCode.trim() || '.<@END@>.'
            })
          })
          return cells;
        },
        // 创建工具条
        createSidebar: function () {
          // var look = yufp.lookup.find('USE_TASK_JOB_TYPE');
          var items = [];
          // if(look && look.length>0){
          //   look.forEach(function(l){
          //     items.push({ img: l.key, title: l.value, data: { nodetype: 'C'}});
          //   })
          // }
          //增加空节点、空模板
          items.push({ img: 'empty', title: '新节点', data: { nodetype: 'VERTEX' } })
          items.push({ img: 'template', title: '模板', data: { nodetype: 'TEMPLATE' } });
          // this.$refs.refWorkflow.setSidebar(items)
          this.$refs.refWorkflow.addToolItems(items);
        },
        celldblclickFn: function (cell) {
          var _this = this;
          this.tabsValue = 'baseMsg';
          this.serverIDDisabled = true;
          this.isPasted = cell.isPasted;
          if (this.isPasted) {
            cell.data.autoUseEventCrossList = [];
            cell.data.useEventCrossList = [];
          }
          this.cell = cell;
          this.getData = cell.data;
          this.nodetype = this.getData.nodetype;
          this.dialogTitle = _this.nodetype === 'EDGE' ? '流转条件' : '作业信息';
          this.showDialog();
          if (_this.nodetype !== 'EDGE') {
            if (_this.nodetype === 'TEMPLATE') {
              _this.isModify = false;
              yufp.service.request({
                method: 'GET',
                url: backend.useService + "/plats/worktemplate/queryTmpList",
                data: { appCode: data.appCode },
                async: false,
                callback: function (code, message, response) {
                  if (response.code != 0) {
                    _this.$message(response.message);
                  } else {
                    _this.template = yufp.clone(response.data, []);
                    _this.templateOptions.splice(0);
                    for (var i = 0; i < response.data.length; i++) {
                      _this.templateOptions.push({ key: response.data[i].actionCode, value: response.data[i].actionName });
                    }
                  }
                }
              });
              return;
            }
            if (_this.nodetype === 'VERTEX') {
              _this.isModify = false;
              _this.$nextTick(function () {
                _this.$refs.refWorkBaseForm.resetFields();
                _this.$refs.refWorkExceForm.resetFields();
                _this.$refs.refWorkAdditionalForm.resetFields();
                yufp.clone({ appCode: data.appCode, success: 0, actionPrior: 5, maxRetry: 0, multiFlag: 'N', intrFlag: 'Y', condType: 'A' }, _this.workBaseFormData);
              });
            } else if (_this.isPasted) { // 复制粘贴的节点
              _this.isModify = false;
              var newCelldata = JSON.parse(JSON.stringify(_this.getData));
              _this.getData = newCelldata;
              _this.cell.data = newCelldata;
              _this.$refs.refWorkflow.updateCell(_this.cell.id, 'data', newCelldata);
              _this.loadData();
            } else {
              _this.isModify = true;
              /*yufp.service.request({
                url: backend.useService + '/plats/workflow/queryJobInfo',
                method: 'get',
                data: {
                  appCode: _this.getData.appCode,
                  groupCode: _this.getData.groupCode,
                  actionCode: _this.getData.actionCode
                },
                callback: function (code, message, response) {
                  if(response && response.data) {
                    _this.getData.relJobs = response.data.relJobs;
                    _this.getData.autoUseEventCrossList = response.data.autoUseEventCrossList;
                    _this.getData.useEventCrossList = response.data.useEventCrossList;
                    _this.loadData();
                  } else {
                    this.$message({message: '作业数据查询失败', type: 'error',showClose:true,duration: 0});
                  }
                }
              });*/
			  if(_this.nodetype  == '-'){
				  _this.nodeExec = '';
			  }else{
				  _this.nodeExec="required";
			  }
              _this.loadData();
            }
          } else {
            _this.$nextTick(function () {
              _this.$refs.refCirculationForm.resetFields();
              _this.getData.remark = typeof _this.getData.remark == 'string' ? _this.getData.remark.split('style=')[0] : '';
              _this.circulationFormData = yufp.extend(true, _this.circulationFormData, _this.getData, {});
            });
          }
        },
        // 添加连线后自动保存连线数据
        connectedFn: function (edge) {
          this.$nextTick(function () {
            this.cell = edge;
            this.getData = edge.data;
            this.saveEdgeForm(true);
          })
        },
        addBtnClickFn: function (cell) { },
        // 删除节点和连线事件
        deleteCell: function (cell) {},
        // 节点拖动事件
        movecell: function (cell) {
          if (cell && cell.id === '.<@START@>.') {
            this.workData.posBeginX = cell.geometry.x;
            this.workData.posBeginY = cell.geometry.y;
          } else if (cell && cell.id === '.<@END@>.') {
            this.workData.posEndX = cell.geometry.x;
            this.workData.posEndY = cell.geometry.y;
          }
        },
        showDialog: function () {
          this.dialogVisible = true;
        },
        /**
         * 弹窗取消关闭按钮事件
         */
        btnCancelFn: function () {
          var _this = this;
          this.dialogVisible = false;
          if (this.nodetype === 'EDGE') {
            _this.$refs.refWorkflow.updateCell(_this.cell.id, 'data', _this.getData);
          }
        },
        /**
         * 基本信息中执行信息新增
         */
        btnAddClickFn: function () {
          var _this = this;
          var status = false;
          if (!_this.getData.wftParList) {
            _this.getData.wftParList = [];
          }
          if (_this.getData.wftParList.length > 0) {
            this.$refs.refTableExec.validate(function (fields) {
              if (!fields) {
                status = true;
              }
            });
            if (!status || _this.getData.wftParList[_this.getData.wftParList.length - 1].paramName === '') {
              this.$message({ message: '请完善数据！', type: 'warning' });
              return;
            }
          }
          _this.getData.wftParList.push({ appCode: _this.workBaseFormData.appCode, paramName: '', paramValue: '', remark: '' });
          _this.$forceUpdate();
        },
        /**
         * 基本信息中执行信息删除
         */
        btnDelClickFn: function () {
          var _this = this;
          var selections = _this.$refs.refTableExec.selections;
          if (selections.length === 0) {
            _this.$message({ message: '请选择表格数据!', type: 'warning' });
            return;
          }
          for (var j = 0; j < selections.length; j++) {
            for (var i = 0; i < _this.getData.wftParList.length; i++) {
              if (_this.getData.wftParList[i].paramName == selections[j].paramName) {
                _this.getData.wftParList.splice(i, 1);
              }
            }
          }
        },
        /**
         * 基本信息中事件信息删除
         */
        btnDelEventsFn: function () {
          var _this = this;
          var selections = _this.$refs.refTableEvents.selections;
          if (selections.length === 0) {
            _this.$message({ message: '请选择表格数据!', type: 'warning' });
            return;
          }
          for (var j = 0; j < selections.length; j++) {
            for (var i = 0; i < _this.getData.useEventCrossList.length; i++) {
              if (_this.getData.useEventCrossList[i].eventCode == selections[j].eventCode) {
                _this.getData.useEventCrossList.splice(i, 1);
              }
            }
          }
        },
        /**
         * 基本信息中事件信息新增
         */
        btnAddEventsFn: function () {
          var _this = this;
          _this.eventVisible = true;
        },
        /**
         * 弹窗保存按钮事件，会根据当前节点类型执行不同的保存操作
         */
        btnSaveFn: function () {
          if (this.nodetype === 'EDGE') {
            this.saveEdgeForm();
          } else {
            this.saveWorkForm();
          }
        },
        /**
         * 保存节点数据
         */
        saveWorkForm: function () {
          var _this = this;
          var model = {};
          var cellId = _this.cell.id;
		  //校验输入的合法性
		  var viflag = true;
		  _this.$refs.refWorkBaseForm.validate(function (valid) {//基本信息
		    viflag = valid;
      });
		  if(!viflag){
			  _this.$message({ message: '请完善基本信息必输内容!', type: 'warning' });
			  return;
		  }
		  _this.$refs.refWorkExceForm.validate(function (valid) { //执行信息
		    viflag = valid;
      });

		  if(!viflag){
			    _this.$message({ message: '请完善执行信息必输内容!', type: 'warning' });
		  	  return;
		  }
		  if(_this.nodeExec =='required' && (_this.workExecFormData.actionExec == '' || _this.workExecFormData.actionExec.trim() == '' )){
			  _this.$message({ message: '请完善执行信息的执行内容!', type: 'warning' });
			  return;
		  }

		  _this.$refs.refWorkAdditionalForm.validate(function (valid) {//附加信息
		    viflag = valid;
		  });
		  if(!viflag){
			   _this.$message({ message: '请完善附加信息必输内容!', type: 'warning' });
		  	  return;
		  }

          if (!_this.workExecFormData.actionExec) {
            _this.workExecFormData.actionExec = ' ';
          }
          _this.workExecFormData.actionLoc = ("-CH".indexOf(_this.workBaseFormData.typeCode)!=-1) ? _this.workExecFormData.actionLoc1 : _this.workExecFormData.actionLoc2;
          yufp.extend(true, model, _this.workBaseFormData, _this.workExecFormData);
          console.info(_this.timepicker);
          model.limitBegin = _this.timepicker ? _this.timepickerList[0] : null;
          model.limitEnd = _this.timepicker ? _this.timepickerList[1] : null;
          // model.limitBegin = _this.workAdditionalFormData.limitBegin;
          // model.limitEnd = _this.workAdditionalFormData.limitEnd;
          model.limitInfo = '';
          if (model.actionCode == '.<@START@>.' || model.actionCode == '.<@END@>.') {
            this.$message({message: '作业代码不能为.<@START@>.或者.<@END@>.!', type:'warning'});
            return;
          }
          // 校验节点ActionCode是否重复
          for (var i in _this.timeList) {
            model.limitInfo += _this.timeList[i].key;
          }
          model.autoUseEventCrossList = _this.getData.autoUseEventCrossList;
          _this.getData.wftParList = _this.getData.wftParList || [];
          model.wftParList = JSON.parse(JSON.stringify(_this.getData.wftParList));
          model.useEventCrossList = _this.getData.useEventCrossList;
          // 关联性校验
          for (var i in model.useEventCrossList) {
            if (model.useEventCrossList[i].relation == '' || model.useEventCrossList[i].relation == null) {
              _this.$message({ message: '请选择事件与作业关联关系!', type: 'warning' });
              return;
            }
          }
          _this.cell.data = yufp.clone(model, {});
          _this.cell.data.nodetype = model.typeCode;
          if(_this.isThisActionCodeOnly(model.actionCode)) {
            model.actionExec = model.actionExec || 'test';
            if (_this.isPasted) { // 复制粘贴的节点
              _this.cell.isPasted = false;
            }
          } else {
            this.$message({message: '作业代码不唯一!', type:'warning'});
            return;
          }
          _this.btnCancelFn();
          // 调用接口成功后更新节点属性
          this.$refs.refWorkflow.updateCellImage(_this.cell);
          this.$refs.refWorkflow.updateCell(cellId, 'label', _this.cell.data.actionName);
          this.$refs.refWorkflow.updateCell(cellId, 'data', _this.cell.data);
          this.$refs.refWorkflow.updateCell(cellId, 'isPasted', _this.cell.isPasted);
          this.$refs.refWorkflow.updateCell(cellId, 'id', _this.cell.data.actionCode);
        },
        isThisActionCodeOnly: function (actionCode) { // 检验 actionCode 是否唯一
          var thisActionCodeNum = 0;
          var cells = this.$refs.refWorkflow.graph.getModel().cells;
          for (var i in cells) {
            var cell = cells[i];
            if (['.<@START@>.', '.<@END@>.'].indexOf(cell.id) === -1 && !cell.children) {
              if (cell.vertex && cell.data.actionCode == actionCode) {
                thisActionCodeNum += 1;
              }
            }
          }
          return thisActionCodeNum < 2;
        },
        /**
         * 连线流转条件保存
         */
        saveEdgeForm: function (isAutoSave) {
          var _this = this;
          var model = { minRet: 0, maxRet: 0, remark: '' };
          var validate = false;
          if (this.$refs.refCirculationForm) {
            this.$refs.refCirculationForm.validate(function (valid) {
              validate = valid;
            });
            if (!validate) {
              return;
            }
          }
          if (this.cell.source === null || this.cell.target === null) {
            this.$message({ message: '连线起点或终点不能为空!', type: 'warning' });
            return;
          }
          if (isAutoSave) {
            yufp.clone(this.getData, model);
          } else {
            yufp.clone(this.circulationFormData, model);
            _this.btnCancelFn();
          }
          // 合并基础数据
          model.condAction = this.cell.source.id;
          model.actionCode = this.cell.target.id;
          model = yufp.extend(true, model, {
            actionCode: ['.<@START@>.', '.<@END@>.'].indexOf(model.actionCode) > -1 ? ' ' : model.actionCode,
            appCode: this.workData.appCode,
            condAction: ['.<@START@>.', '.<@END@>.'].indexOf(model.condAction) > -1 ? ' ' : model.condAction,
            flowPath: '',
            groupCode: this.workData.groupCode,
            nodetype: "EDGE",
            remark: model.remark || '',
            drawInfo: this.cell.style || '',
            version: 1
          })
          var edgeId = (model.condAction.trim() || '.<@START@>.') + '-' + (model.actionCode.trim() || '.<@END@>.');
          _this.$refs.refWorkflow.updateCell(_this.cell.id, 'data',  model);
          _this.$refs.refWorkflow.updateCell(_this.cell.id, 'id', edgeId);
        },
        /**
         * 系统事件树过滤方法
         */
        filterNode: function (value, data, node) {
          if (!value) {
            return true;
          }
          return data.label.indexOf(value) !== -1;
        },
        /**
         * 时间选择事件
         */
        timeSelectFn: function (val) {
          this.selectTime = val;
        },
        /**
         * 添加时间
         */
        addFn: function () {
          if (this.workAdditionalFormData.radio1) {
            if (!this.workAdditionalFormData.date) {
              this.$message({ message: '请输入日期', type: 'warning' });
              return;
            }
            var value = (this.workAdditionalFormData.date.getMonth() + 1 > 9 ? this.workAdditionalFormData.date.getMonth() + 1 : '0' + (this.workAdditionalFormData.date.getMonth() + 1)) + '月' + (this.workAdditionalFormData.date.getDate() < 10 ? '0' + this.workAdditionalFormData.date.getDate() : this.workAdditionalFormData.date.getDate()) + '日';
            var key = '' + (this.workAdditionalFormData.date.getMonth() + 1 > 9 ? this.workAdditionalFormData.date.getMonth() + 1 : '0' + (this.workAdditionalFormData.date.getMonth() + 1)) + (this.workAdditionalFormData.date.getDate() < 10 ? '0' + this.workAdditionalFormData.date.getDate() : this.workAdditionalFormData.date.getDate());
            for (var i in this.timeList) {
              if (this.timeList[i].key == key) {
                this.$message({ message: '请添加不同日期', type: 'warning' });
                this.workAdditionalFormData.date = '';
                return;
              }
            }
            this.timeList.push({ key: key, value: value });
            this.workAdditionalFormData.date = '';
          } else if (this.workAdditionalFormData.radio2) {
            var flag = this.workAdditionalFormData.day && this.workAdditionalFormData.date1 && this.workAdditionalFormData.date2;
            if (!flag) {
              this.$message({ message: '请输入完整日期', type: 'warning' });
              return;
            }
            if (isNaN(this.workAdditionalFormData.day)) {  //校验天为数字
              return;
            }
            //增加数字限制检验规则

            this.$refs.refWorkAdditionalForm.validateField('day', dayError => {
              if (dayError) {
                this.$refs.dayref.fields.error = 'error'
                return;
              }

            });

            var key = this.workAdditionalFormData.date1 + this.workAdditionalFormData.date2 + (this.workAdditionalFormData.day < 10 ? '0' + this.workAdditionalFormData.day : this.workAdditionalFormData.day);
            // var value = yufp.lookup.convertKey('USE_FIXED_TIME_RANGE', this.workAdditionalFormData.date1) + yufp.lookup.convertKey('USE_FIXED_TIME_F', this.workAdditionalFormData.date2) + (this.workAdditionalFormData.day < 10 ? '0' + this.workAdditionalFormData.day : this.workAdditionalFormData.day) + '天';
            var value = '';
            if (this.workAdditionalFormData.date1 == "W") {
              //翻译为具体的星期名
              var num = 0;//周初为星期日\
              var dayNum = parseInt(this.workAdditionalFormData.day);
              if (this.workAdditionalFormData.date2 == "+") {
                num = num + dayNum;
              } else {
                num = 6 - dayNum;
              }
              value = "星期" + this.weekMap[num];
              // this.dayList.push({ key: value, value: key });标记
            } else {
              value = yufp.lookup.convertKey('USE_FIXED_TIME_RANGE', this.workAdditionalFormData.date1) + yufp.lookup.convertKey('USE_FIXED_TIME_F', this.workAdditionalFormData.date2) + (this.workAdditionalFormData.day < 10 ? '0' + this.workAdditionalFormData.day : this.workAdditionalFormData.day) + '天';
            }
            for (var i in this.timeList) {
              if (this.timeList[i].key == key) {
                this.$message({ message: '请添加不同日期', type: 'warning' });
                this.workAdditionalFormData.day = '';
                return;
              }
            }
            this.timeList.push({ key: key, value: value });
            this.workAdditionalFormData.day = '';
          } else if (this.workAdditionalFormData.radio3) {
            var value = '';
            if (!this.workAdditionalFormData.datetype) {
              this.$message({ message: '请输入完整日期类型', type: 'warning' });
              return;
            }
            for (var i in this.dateTypeOptions) {
              if (this.dateTypeOptions[i].key == this.workAdditionalFormData.datetype) {
                value = this.dateTypeOptions[i].value;
                break;
              }
            }
            for (var j in this.timeList) {
              if (this.timeList[j].key.slice(0, 3) === '@DT' && this.timeList[j].key.slice(3) == this.workAdditionalFormData.datetype) {
                this.$message({ message: '请添加不同日期类型', type: 'warning' });
                this.workAdditionalFormData.datetype = '';
                return;
              }
            }
            this.timeList.push({ key: "@DT" + this.dateTypeOptions[i].key, value: this.dateTypeOptions[i].value });
            this.workAdditionalFormData.datetype = '';
          }
        },
        /**
         * 删除时间
         */
        deleteFn: function () {
          if (!this.selectTime) {
            this.$message({ message: '请选择日期', type: 'warning' });
          }
          this.timeList.splice(this.timeList.indexOf(this.selectTime), 1);
          this.selectTime = {};
        },
        /**
         * 依赖作业树
         */
        focusFn: function () {
          var _this = this;
          _this.visible = true;
          _this.$nextTick(function () {
            var searchData = {};
            searchData.appCode = _this.workBaseFormData.appCode;
            searchData.groupCode = data.groupCode;
            // searchData.actionCode = _this.workBaseFormData.actionCode;
            var param = { condition: JSON.stringify(searchData) };
            _this.$refs.jobTableRef.remoteData(param);
          })
        },
        /**
         * 保存依赖作业
         */
        saveFn: function () {
          var _this = this;
          var arr = [];
          var select = _this.$refs.workTree.getCheckedNodes(true);
          if (select.length !== 0) {
            _this.workBaseFormData.relJobs = '';
            _this.getData.autoUseEventCrossList.splice(0);
          }
          for (var i = 0; i < select.length; i++) {
            if (select[i].nodeType !== 'D') {
              continue;
            }
            _this.getData.autoUseEventCrossList.push({ appCode: data.appCode, groupCode: select[i].groupCode, actionCode: select[i].actionCode });
            _this.getSlectId.push(select[i].id);
            _this.workBaseFormData.relJobs = _this.workBaseFormData.relJobs + select[i].actionCode + (select.length === 1 ? '' : ';');
          }
          _this.visible = false;
        },
        /**
         * 清空依赖作业
         */
        clearFn: function () {
          this.getSlectId.splice(0);
          this.getData.autoUseEventCrossList.splice(0);
          this.workBaseFormData.relJobs = '';
          this.getData.relJobs = '';
          this.$refs.workTree.setCheckedNodes([]);
        },
        // 保存流程图作业
        saveDataFn: function () {
          var _this = this;
          var valid = this.$refs.refWorkflow.checkValidate();
          if (valid) {
            this.$msgbox({
              title: '提示',
              message: valid,
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'warning'
            });
            return;
          }
          var cells = _this.$refs.refWorkflow.graph.getModel().cells;
          this.workData.wftCndList = [];
          this.workData.wftLstList = [];
          for (var i in cells) {
            var cell = cells[i];
            if (['.<@START@>.', '.<@END@>.'].indexOf(cell.id) === -1 && !cell.children) {
              if (cell.edge) {
                if (!cell.data) {
                  this.$message({message:'页面含未保存数据!', type:'warning'});
                  return;
                } else {
                  cell.data.remark = cell.data.remark || '';
                  cell.data.minRet = cell.data.minRet || 0;
                  cell.data.maxRet = cell.data.maxRet || 0;
                  cell.data.drawInfo = cell.style || '',
                  _this.workData.wftCndList.push(cell.data);
                }
              } else {
                if (!cell.data.actionCode) {
                  this.$message({message:'页面含未保存数据!', type:'warning'});
                  return;
                } else {
                  _this.workData.wftLstList.push(cell.data);
                }
              }
            }
          }
          var isNoRepeat = true;
          this.workData.wftLstList.forEach(function (item, index) {
            for (var i = index + 1; i < _this.workData.wftLstList.length; i++) {
              if (_this.workData.wftLstList[i].actionCode == item.actionCode) {
                isNoRepeat = false;
              }
            }
            item.wftParList = item.wftParList || [];
            item.wftParList.forEach(function (params, index) {
              params.paramNo = index + 1;
            })
          });
          if (!isNoRepeat) {
            this.$message({ message: '作业代码不唯一!', type: 'warning' });
            return;
          }
          if (this.workData.wftLstList.length === 0) {
            this.$message({ message: '没有节点!', type: 'warning' });
            return;
          }
          this.setWorkDataCellCoordinate();
          var flowContent = this.$refs.refWorkflow.exportXML();
          if (flowContent) {
            if (!this.workData.pageSizeX) {
              this.workData.pageSizeX = 0;
            }
            yufp.service.request({
              url: backend.useService + '/plats/workflow/saveFlowChart',
              method: 'POST',
              data: _this.workData,
              callback: function (code, message, res) {
                if (res.code === 0) {
                  _this.$message({ message: '保存成功', type: 'success' });
                } else {
                  _this.$message({ message: res.message, type: 'error', showClose: true, duration: 0 });
                }
              }
            })
          }
        },
        // 设置workData中节点的坐标
        setWorkDataCellCoordinate: function () {
          var _this = this;
          var cells = _this.$refs.refWorkflow.graph.getModel().cells;
          var coordinateObj = _this.$refs.refWorkflow.getCellsCoordinate();
          _this.workData.rngMinX = Math.round(coordinateObj.rngMinX / _this.scale);
          _this.workData.rngMinY = Math.round(coordinateObj.rngMinY / _this.scale);
          _this.workData.rngMaxX = Math.round(coordinateObj.rngMaxX / _this.scale);
          _this.workData.rngMaxY = Math.round(coordinateObj.rngMaxY / _this.scale);
          _this.workData.pageSizeX = _this.workData.rngMaxX - _this.workData.rngMinX;
          _this.workData.pageSizeY = _this.workData.rngMaxY - _this.workData.rngMinY;
          _this.workData.positionX = 0;
          _this.workData.positionY = 0;
          for (var i in cells) {
            var cell = cells[i];
            if (cell.vertex) {
              var x = cell.geometry.x - coordinateObj.rngMinX + 25;
              var y = (cell.geometry.y - coordinateObj.rngMaxY + 25) * -1;
              x = Math.round(x / _this.scale);
              y = Math.round(y / _this.scale);
              if (cell.id === '.<@START@>.') {
                _this.workData.posBeginX = x;
                _this.workData.posBeginY = y;
                var data = { nodetype: '.<@START@>.', positionX: x, positionY: y };
                _this.$refs.refWorkflow.updateCell(cell.id, 'data', data);
              } else if (cell.id === '.<@END@>.') {
                _this.workData.posEndX = x;
                _this.workData.posEndY = y;
                var data = { nodetype: '.<@END@>.', positionX: x, positionY: y };
                _this.$refs.refWorkflow.updateCell(cell.id, 'data', data);
              } else {
                _this.workData.wftLstList.forEach(function (item) {
                  if (item.actionCode === cell.id) {
                    item.positionX = x;
                    item.positionY = y;
                    _this.$refs.refWorkflow.updateCell(cell.id, 'data', item);
                  }
                })
              }
            }
          }
          this.workData.wftCndList.forEach(function (item) {
            var condAction = item.condAction != ' ' ? item.condAction : '.<@START@>.';
            var actionCode = item.actionCode != ' ' ? item.actionCode : '.<@END@>.';
            var edgeId = condAction + '-' + actionCode;
            var path = _this.$refs.refWorkflow.getEdgeCellPath(edgeId, coordinateObj.rngMinX, coordinateObj.rngMaxY);
            item.flowPath = path ? path : item.flowPath;
            item.minRet = item.minRet || 0;
            item.maxRet = item.maxRet || 0;
            if (item.condAction == '.<@START@>.') {
              item.condAction = ' ';
            }
            if (item.actionCode == '.<@END@>.') {
              item.actionCode = ' ';
            }
          });
        },
        selectLastCellFn: function (selectionCell, otherCells) {
          this.selectionCell = selectionCell;
          this.tableCells = otherCells;
          this.isSelectNextCell = false;
          this.selectCellDialogTitle = '请选择依赖的作业';
          this.multipleSelection = [];
          this.showSelectCellDialog = true;

        },
        selectNextCellFn: function (selectionCell, otherCells) {
          this.selectionCell = selectionCell;
          this.tableCells = otherCells;
          this.isSelectNextCell = true;
          this.selectCellDialogTitle = '请选择触发的作业';
          this.multipleSelection = [];
          this.showSelectCellDialog = true;
        },
        handleSelectionChange: function (val) {
          this.multipleSelection = val;
        },
        confirmSelectCell: function () {
          var _this = this;
          if (this.multipleSelection.length === 0) {
            this.$message({ message: '请至少选中一条数据！', type: 'warning' });
            return;
          }
          var edgesData = [];
          this.multipleSelection.forEach(function (item) {
            var id, source, target;
            if (_this.isSelectNextCell) {
              source = _this.selectionCell.actionCode ? _this.selectionCell.actionCode.trim() : '.<@START@>.';
              target = item.actionCode ? item.actionCode.trim() : '.<@END@>.';
            } else {
              source = item.actionCode ? item.actionCode.trim() : '.<@START@>.';
              target = _this.selectionCell.actionCode ? _this.selectionCell.actionCode.trim() : '.<@END@>.';
            }
            id = source + '-' + target;
            edgesData.push({
              nodetype: 'EDGE',
              id: id,
              value: '',
              path: '',
              remark: '',
              style: '',
              source: source,
              target: target,
              data: {
                appCode: _this.workData.appCode,
                groupCode: _this.workData.groupCode,
                condCode: ['.<@START@>.', '.<@END@>.'].indexOf(target) > -1 ? ' ' : source,
                actionCode: ['.<@START@>.', '.<@END@>.'].indexOf(source) > -1 ? ' ' : target,
                minRet: 0,
                maxRet: 0,
                flowPath: '',
                remark: '',
                version: 1
              }
            })
          });
          this.$refs.refWorkflow.addEdgeList(null, edgesData, true);
          this.cancelSelectCell();
        },
        cancelSelectCell: function () {
          this.tableCells = [];
          this.multipleSelection = [];
          this.showSelectCellDialog = false;
        },
        /**
         * 取消
         */
        cancelFn: function () {
          var _this = this;
          _this.visible = false;
        },
        /**
         * 搜索事件
         */
        searchFn: function () {
          var _this = this;
          var tree = [];
          if (!_this.filterText) {
            _this.treeTempData = _this.treeData;
            return;
          }
          _this.treeTempData = _this.treeData.filter(function (item) {
            var flag = false;
            tree = _this.getTree(item);
            for (var i = 0; i < tree.length; i++) {
              if (tree[i].id == _this.filterText) {
                flag = true;
                break;
              }
            }
            return flag;
          });
        },
        /**
         * 开始时间限制
         */
        limitBeginFn: function () {
          var _this = this;
          var message;
          _this.$refs.refWorkAdditionalForm.validateField('limitBegin', function (msg) {
            message = msg;
          });
          if (message) {
            return;
          }
          var limitEnd = _this.workAdditionalFormData.limitEnd.trim() !== '' && _this.workAdditionalFormData.limitEnd !== null && _this.workAdditionalFormData.limitEnd !== undefined;
          var limitBegin = _this.workAdditionalFormData.limitBegin.trim() !== '' && _this.workAdditionalFormData.limitBegin !== null && _this.workAdditionalFormData.limitBegin !== undefined;
          if (limitEnd && limitBegin) {
            if (+_this.workAdditionalFormData.limitBegin > +_this.workAdditionalFormData.limitEnd) {
              _this.$message({ message: '开始时间不能大于结束时间!', type: 'warning' });
              _this.workAdditionalFormData.limitBegin = '';
            }
          }
        },
        /**
         * 结束时间限制
         */
        limitEndFn: function () {
          var _this = this;
          var message;
          _this.$refs.refWorkAdditionalForm.validateField('limitEnd', function (msg) {
            message = msg;
          });
          if (message) {
            return;
          }
          var limitEnd = _this.workAdditionalFormData.limitEnd.trim() !== '' && _this.workAdditionalFormData.limitEnd !== null && _this.workAdditionalFormData.limitEnd !== undefined;
          var limitBegin = _this.workAdditionalFormData.limitBegin.trim() !== '' && _this.workAdditionalFormData.limitBegin !== null && _this.workAdditionalFormData.limitBegin !== undefined;
          if (limitEnd && limitBegin) {
            if (+_this.workAdditionalFormData.limitBegin > +_this.workAdditionalFormData.limitEnd) {
              _this.$message({ message: '结束时间不能小于开始时间!', type: 'warning' });
              _this.workAdditionalFormData.limitEnd = '';
            }
          }
        },
        /**
         * 选取模板类型下一步
         */
        nextFn: function () {
          var _this = this;
          _this.$refs.modelForm.validate(function (valid) {
            validate = valid;
          });
          if (!validate) {
            return;
          }
          for (var i = 0; i < _this.template.length; i++) {
            if (_this.template[i].actionCode === _this.modelForm.templateType) {
              _this.getData = yufp.clone(_this.template[i], {});
              _this.getData.wftParList = _this.getData.useCatalogParamList;
              break;
            }
          }
          _this.nodetype = _this.template[i].typeCode;
          _this.loadData();
        },
        /**
         * 加载节点数据
         */
        loadData: function () {
          var _this = this;
          _this.timepickerList.splice(0);
          _this.timepicker = [];
          if (_this.getData.limitBegin !== null && _this.getData.limitBegin !== undefined && _this.getData.limitBegin !== "" && _this.getData.limitBegin !== " ") {
            _this.timepicker.push(new Date(2020, 5, 29, _this.getData.limitBegin.substring(0, 2), _this.getData.limitBegin.substring(2, 4), _this.getData.limitBegin.substring(4, 6)));
            _this.timepicker.push(new Date(2020, 5, 29, _this.getData.limitEnd.substring(0, 2), _this.getData.limitEnd.substring(2, 4), _this.getData.limitEnd.substring(4, 6)));
            _this.timepickerList.push(_this.getData.limitBegin);
            _this.timepickerList.push(_this.getData.limitEnd);
          }
          _this.$nextTick(function () {
            _this.$refs.refWorkBaseForm.resetFields();
            _this.$refs.refWorkExceForm.resetFields();
            _this.$refs.refWorkAdditionalForm.resetFields();
            _this.getData2Form(_this.getData);
            _this.workExecFormData.actionLoc1 = _this.getData.actionLoc;
            _this.workExecFormData.actionLoc2 = _this.getData.actionLoc;
            _this.workExecFormData.actionExec = _this.getData.actionExec;
            if ((_this.workBaseFormData.actionPrior == null || _this.workBaseFormData.actionPrior == '') && (_this.workBaseFormData.maxRetry == null || _this.workBaseFormData.maxRetry == '') && (_this.workBaseFormData.condType == null || _this.workBaseFormData.condType == '')) {
              yufp.clone({ actionPrior: 5, maxRetry: 0, condType: 'A' }, _this.workBaseFormData);
            }
          });
        },
        /**
         * 切换下一个tab视图
         */
        nextToFn: function () {
          var _this = this;
          var validate = true;
          var tabs = ['baseMsg', 'exceMsg', 'moreMsg', 'eventMsg'];
          if (_this.tabsValue === 'baseMsg') {
            _this.$refs.refWorkBaseForm.validate(function (valid) {
              validate = valid;
            });
          } else if (_this.tabsValue === 'exceMsg') {
            _this.$refs.refWorkExceForm.validate(function (valid) {
              validate = valid;
            });
            if (validate) {
              // 校验表格数据
              this.$refs.refTableExec.validate(function (fields) {
                if (fields) {
                  validate = false;
                }
              });
            }
          }
          if (!validate) {
            return;
          }
          if (_this.isExce && _this.tabsValue === 'baseMsg') {
            _this.tabsValue = tabs[tabs.indexOf(_this.tabsValue) + 2];
          } else {
            _this.tabsValue = tabs[tabs.indexOf(_this.tabsValue) + 1];
          }
        },
        /**
         * 切换上一个tab视图
         */
        lastFn: function () {
          var _this = this;
          var tabs = ['baseMsg', 'exceMsg', 'moreMsg', 'eventMsg'];
          if (_this.isExce && _this.tabsValue === 'moreMsg') {
            _this.tabsValue = tabs[tabs.indexOf(_this.tabsValue) - 2];
          } else {
            _this.tabsValue = tabs[tabs.indexOf(_this.tabsValue) - 1];
          }
        },
        timepickerChange: function (value) {
          this.timepickerList.splice(0);
          this.timepickerList.push(value[0]);
          this.timepickerList.push(value[1]);
        }
      }
    });
  };

  /**
   * 页面传递消息处理
   * @param type 消息类型
   * @param message 消息内容
   */
  exports.onmessage = function (type, message, cite, vm) {
    if (type === 'active-tab') {
      vm.$refs.refWorkflow.hiddenOutlineWindow(false);
    }
    if (type === 'active-tab-self') {
      vm.$refs.refWorkflow.hiddenOutlineWindow(true);
    }
  };

  /**
   * 页面销毁时触发destroy方法
   * @param id 路由ID
   * @param cite 页面站点信息
   */
  exports.destroy = function (id, cite) {
  };
});
